package com.gxljc.bear.crawler.weixin;

import com.gxljc.commons.util.AdvFile;
import com.gxljc.commons.util.ILineParser;
import com.gxljc.commons.util.StringUtil;
import com.gxljc.bear.crawler.base.DolphinCrawlerConf;
import org.apache.hadoop.conf.Configuration;
import org.apache.log4j.Logger;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;

public class WeixinAccountConf implements Serializable {
    private static final long serialVersionUID = 1L;
    private static Logger LOG = Logger.getLogger(WeixinAccountConf.class);
    private static HashMap<String, String> bizMap = new HashMap<>();
    private static HashMap<String, AccountTable> accountMap = new HashMap<>();


    private static final WeixinAccountConf config = new WeixinAccountConf();

    private WeixinAccountConf() {
        try {
            initConfiguration();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public HashMap<String, String> getBizMap(){
        return bizMap;
    }

    public HashMap<String, AccountTable> getAccountMap(){
        return accountMap;
    }

    public static WeixinAccountConf getInstance() {
        return config;
    }

    private void initConfiguration() throws Exception {
        getAccountSeedMap();
        getAllBizMap();
    }

    private void getAccountSeedMap() throws Exception {
        HashMap<String, AccountTable> map = new HashMap<>();
        try {
            List<AccountTable> seeds = WeixinUtil.getAccountSeed();
            for (AccountTable seed : seeds) {
                accountMap.put(seed.accountId, seed);
            }
            return ;
        } catch (Exception ex) {
            ex.printStackTrace();
            return ;
        }
    }

    private void getAllBizMap() throws Exception {
        final String filename = "weixin_biz_all.txt";
        Configuration conf = DolphinCrawlerConf.getInstance();
        AdvFile.loadFileInDelimitLine(
                conf.getConfResourceAsInputStream(filename), new ILineParser() {
                    @Override
                    public void parseLine(String line) {
                        String[] split = line.split(StringUtil.STR_DELIMIT_3RD);
                        if (split.length != 2) {
                            return;
                        }
                        String accountID = split[0].trim();
                        String biz = split[1].trim();
                        if (biz.isEmpty() || accountID.isEmpty() ) {
                            return;
                        }
                        bizMap.put(biz, accountID);
                    }
                });
    }
}
